<?php
/**
 * SLS_BoEmail Tool - Generate back-office emailing
 *  
 * @author Laurent Bientz 
 * @copyright SillySmart
 * @package SLS.Generics.Tools.SLS_Bo
 * @since 1.0.8
 */
class SLS_BoEmail
{		
	private $oController;
	private $model;
	private $db;
	private $_generic;
	private $_http;	
	private $urlToRedirect;
	private $refSmod;
			
	/**
	 * Constructor
	 *
	 * @access public
	 * @param object $oController reference of the current running controller
	 * @param string $model the model you want to allow adding	 
	 * @param string $alias the alias of the db
	 * @since 1.0
	 */
	public function __construct($oController,$model,$alias)
	{
		$this->oController = $oController;
		$this->model = $model;
		$this->db = $alias;
		$this->_generic = SLS_Generic::getInstance();
		$this->_http = $this->_generic->getObjectHttpRequest();
	}
	
	/**
	 * Construct the clone
	 *
	 * @access public
	 * @since 1.0
	 */
	public function constructEmail($xml)
	{
		$id = explode("|",$this->_http->getParam("id"));
		$tpl = $this->_http->getParam("tpl");
		$item = strtolower($this->db."_".$this->model);
		$db = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($item,"_")));
		$model = SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($item,"_"));
		$class = $db."_".$model;
		$mailXML = $this->_generic->getMailXML();
		$xmlType = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml"));
		$this->_generic->useModel($model,$db);
		$object = new $class();
		$templates = $mailXML->getTags("//mails/templates/item/@id");
		$errors = array();
		$columnEmail = $xmlType->getTag("//sls_configs/entry[@table='".$object->getDatabase()."_".$object->getTable()."' and @type = 'email']/@column");
		$columns = $object->getColumns();
				
		$fromEmail 		= $this->_generic->getMailConfig("defaultSender")."@".$this->_generic->getMailConfig("defaultDomain");
		$replyEmail 	= $this->_generic->getMailConfig("defaultReply")."@".$this->_generic->getMailConfig("defaultDomain");
		$returnEmail 	= $this->_generic->getMailConfig("defaultReturn")."@".$this->_generic->getMailConfig("defaultDomain");
		$fromName 		= $this->_generic->getMailConfig("defaultNameSender");
		$replyName 		= $this->_generic->getMailConfig("defaultNameReply");
		$returnName 	= $this->_generic->getMailConfig("defaultNameReturn");
		
		if ($this->_http->getParam("template") != "")
			$this->_generic->forward($this->_generic->getGenericControllerName(),$this->_generic->getGenericScontrollerName(),array(array("key"=>"id","value"=>$this->_http->getParam("id")),array("key"=>"tpl","value"=>$this->_http->getParam("template"))));
		if ($this->_http->getParam("tpl") == "" && count($templates) == 1)
			$this->_generic->forward($this->_generic->getGenericControllerName(),$this->_generic->getGenericScontrollerName(),array(array("key"=>"id","value"=>$this->_http->getParam("id")),array("key"=>"tpl","value"=>$templates[0])));
		if ($this->_http->getParam("tpl") == "" && count($templates) == 0)		
			$this->_generic->forward($this->_generic->getGenericControllerName(),$this->_generic->getGenericScontrollerName(),array(array("key"=>"id","value"=>$this->_http->getParam("id")),array("key"=>"tpl","value"=>"sls_no_tpl")));
		
		if ($this->_http->getParam("reload_email") === "true")
		{
			$subject 		= SLS_String::trimSlashesFromString($this->_http->getParam("subject"));
			$message 		= SLS_String::trimSlashesFromString($this->_http->getParam("message"));
			$fromEmail 		= SLS_String::trimSlashesFromString($this->_http->getParam("from_email"));
			$replyEmail 	= SLS_String::trimSlashesFromString($this->_http->getParam("reply_email"));
			$returnEmail 	= SLS_String::trimSlashesFromString($this->_http->getParam("return_email"));
			$fromName 		= SLS_String::trimSlashesFromString($this->_http->getParam("from_name"));
			$replyName 		= SLS_String::trimSlashesFromString($this->_http->getParam("reply_name"));
			$returnName 	= SLS_String::trimSlashesFromString($this->_http->getParam("return_name"));
			
			if (empty($fromName))
				array_push($errors,$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_EMAIL_FROM_NAME']." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_EMPTY']);
			if (!SLS_String::validateEmail($fromEmail))
				array_push($errors,$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_EMAIL_FROM_EMAIL']." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_TYPE']);			
			if (empty($replyName))
				array_push($errors,$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_EMAIL_REPLY_NAME']." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_EMPTY']);
			if (!SLS_String::validateEmail($replyEmail))
				array_push($errors,$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_EMAIL_REPLY_EMAIL']." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_TYPE']);			
			if (empty($returnName))
				array_push($errors,$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_EMAIL_RETURN_NAME']." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_EMPTY']);
			if (!SLS_String::validateEmail($returnEmail))
				array_push($errors,$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_EMAIL_RETURN_EMAIL']." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_TYPE']);			
			if (empty($subject))
				array_push($errors,$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_EMAIL_SUBJECT']." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_EMPTY']);
			if (empty($message))
				array_push($errors,$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_EMAIL_MESSAGE']." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_EMPTY']);
				
			if (empty($errors))
			{
				foreach($id as $pk)
				{
					if ($object->getModel($pk) === true)
					{
						$search = array();
						$replace = array();
						foreach($object->getParams() as $key => $value)
						{
							array_push($search,"||".$key."||");
							array_push($replace,$value);
						}
						$message = str_replace($search,$replace,$message);
						
						$email = new SLS_Email(SLS_Security::getInstance()->decrypt($this->_generic->getMailConfig("host"),$this->_generic->getSiteConfig("privateKey")),
											   SLS_Security::getInstance()->decrypt($this->_generic->getMailConfig("port"),$this->_generic->getSiteConfig("privateKey")),
											   SLS_Security::getInstance()->decrypt($this->_generic->getMailConfig("username"),$this->_generic->getSiteConfig("privateKey")),
											   SLS_Security::getInstance()->decrypt($this->_generic->getMailConfig("password"),$this->_generic->getSiteConfig("privateKey")));
						$email->openConnection();
						$email->setCharset("UTF-8");
						$email->addRecipient($object->__get($columnEmail), "To");      
						$email->setSender($fromEmail, $fromName);
						$email->setReply($replyEmail, $replyName);
						$email->setReturn($returnEmail, $returnName);
						$email->setSubject(SLS_String::makeEmailSubject($subject));			
						$email->setHtml(mb_convert_encoding($message,"UTF-8","UTF-8"));
						$email->setPlain(strip_tags(SLS_String::br2nl($message)));
						$email->compileMail();
						$email->send();
						$email->closeConnection();	
					}
				}
				$xml->addFullTag("success",$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_EMAIL_SUCCESS'],true);
			}
			else
			{
				$xml->startTag("errors");
				foreach($errors as $error)
					$xml->addFullTag("error",$error,true);
				$xml->endTag("errors");
			}
		}
		
		$xml->startTag("templates");
		for($i=0 ; $i<$count=count($templates) ; $i++)
		{			
			$tpl_id = $templates[$i];
			$header = $mailXML->getTag("//mails/templates/item[@id='".$tpl_id."']/header");
			$footer = $mailXML->getTag("//mails/templates/item[@id='".$tpl_id."']/footer");
			$xml->startTag("template");
				$xml->addFullTag("id",$tpl_id,true);
				$xml->addFullTag("header",$header,true);
				$xml->addFullTag("footer",$footer,true);
			$xml->endTag("template");
		}
		$xml->endTag("templates");
		
		$xml->startTag("columns");
		foreach($columns as $column)
		{
			$xml->startTag("column");
				$xml->addFullTag("name",$column,true);
				$xml->addFullTag("comment",$object->getColumnComment($column,$object->getTable(),$object->getDatabase()),true);
			$xml->endTag("column");
		}
		$xml->endTag("columns");
		
		$xml->startTag("infos");
			$xml->addFullTag("tpl",$tpl,true);
			$xml->addFullTag("subject",$subject,true);
			$xml->addFullTag("message",$message,true);
			$xml->addFullTag("from_email",$fromEmail,true);
			$xml->addFullTag("reply_email",$replyEmail,true);
			$xml->addFullTag("return_email",$returnEmail,true);
			$xml->addFullTag("from_name",$fromName,true);
			$xml->addFullTag("reply_name",$replyName,true);
			$xml->addFullTag("return_name",$returnName,true);
			$objects = $object->searchModels($object->getTable(),array(),array(array("column"=>$object->getPrimaryKey(),"value"=>$id,"mode"=>"in")));			
			$xml->startTag("recipients");
			for($i=0 ; $i<$count=count($objects) ; $i++)			
				$xml->addFullTag("recipient",$objects[$i]->$columnEmail,true);			
			$xml->endTag("recipients");
		$xml->endTag("infos");
		
		$xml->addFullTag("tpl_choose",(!empty($tpl)) ? "true" : "false");
		
		return $xml;
	}
}
?>